var Tally = require('../models/tally');
var express = require('express');
var router = express.Router();

router.route('/tally')

    // create a bear (accessed at POST http://localhost:8080/api/bears)
    .post(function(req, res) {
        
        var tally = new Tally();      // create a new instance of the Bear model
        tally.user = req.body.user; 
        tally.billsdue = req.body.billsdue;
        tally.note = req.body.note;
        tally.date = req.body.date;
        tally.pay = req.body.pay;
        tally.billhistory = req.body.billhistory;
       // mg.date = new Date();
        // save the bear and check for errors
        tally.save(function(err) {
            if (err)
                res.json({message: 'failed'});
            res.json({ message: 'tally created!' });
        });   
    })

    .get(function(req, res) {
      Tally.find(function(err, message) {
        if (err) {
         return res.send(err);
        }
        res.json(message);
      })
    });

router.route('/tally/:username')
  .get(function(req,res){
    Tally.find({'user':req.params.username},function(err,tally){
      if (err)
         res.json({success: false});
       res.json(tally);
    });
});

router.route('/tally/pay/:id')
  .put(function(req,res) {
    Tally.findById(req.params.id,function(err,tally){
      if (err)
         res.json({success: false});
       if(tally.billsdue){
         tally.billsdue = 0;
         tally.pay = "已付";
       }

        tally.save(function(err){
            if (err)
                 res.json({success: false});
              res.json({ message: 'billsdue was updated!',success: true });
        });   
    });
  });

module.exports = router;